package com.feiyi.app.activity;

import android.media.Image;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.feiyi.app.R;
import com.feiyi.app.adapter.CheckOrderAdapter;
import com.feiyi.app.app.AppConstant;
import com.feiyi.app.base.BaseActivity;
import com.feiyi.app.bean.AddressListBean;
import com.feiyi.app.bean.CheckOrderBean;
import com.feiyi.app.bean.MyYouhuiBean;
import com.feiyi.app.bean.OrderDoneBean;
import com.feiyi.app.event.BonusChooseEvent;
import com.feiyi.app.event.ChooseAddressEvent;
import com.feiyi.app.net.HttpMethods;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;
import okhttp3.RequestBody;

/**
 * @author wangliantao
 * @time 2018 12 2018/12/9 5:22 PM
 * @email 1346947404@qq.com
 * @package com.feiyi.app.activity
 * @describe： In me the tiger sniffs the rose
 */
public class SubmitOrderActivity extends BaseActivity {

    Unbinder unbinder ;
    @BindView(R.id.tv_title_titlebar)
    TextView tvTitleBar;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_mobile)
    TextView tv_mobile;
    @BindView(R.id.iv_default)
    ImageView iv_default;
    @BindView(R.id.tv_address_detail)
    TextView tv_address_detail;
    @BindView(R.id.rl_address)
    RelativeLayout rl_address;
    @BindView(R.id.rv_goods)
    RecyclerView rv_goods;
    @BindView(R.id.ll_bonus)
    LinearLayout ll_bonus;
    @BindView(R.id.tv_bonus)
    TextView tv_bonus;
    @BindView(R.id.tv_price_total)
    TextView tv_price_total;
    @BindView(R.id.tv_bonus_price)
    TextView tv_bonus_price;
    @BindView(R.id.cb_alipay_checked)
    CheckBox cb_alipay;
    @BindView(R.id.cb_wechat_checked)
    CheckBox cb_wechat;
    @BindView(R.id.tv_total_price_all)
    TextView tv_total_price_all;

    private CheckOrderAdapter mAdapter;

    private List<CheckOrderBean.DataBean.GoodsListBean> mList = new ArrayList<>();

    private CheckOrderBean checkOrderBeanLocal;

    private String uid;

    private String sid;

    private static final String TAG = "main";

    private String rec_id;

    private String pay_id = "1";//1是支付宝，2是财付通

    private MyYouhuiBean.DataBean youhuiData;

    private String address_id;

    private String bonus;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit_order);
        unbinder = ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initView();
        initData();
    }

    private void initView() {
        tvTitleBar.setText("填写订单");
        rv_goods.setNestedScrollingEnabled(false);
        rv_goods.setLayoutManager(new LinearLayoutManager(this));
        rv_goods.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mAdapter = new CheckOrderAdapter(R.layout.item_checkorder,mList);
        rv_goods.setAdapter(mAdapter);
        cb_alipay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    pay_id = "1";
                }
            }
        });
        cb_wechat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    pay_id = "2";
                }
            }
        });
    }

    private void initData() {
        uid = spUtils.getString(AppConstant.UID);
        sid = spUtils.getString(AppConstant.SID);
        rec_id = getIntent().getStringExtra("rec_id");

        new Thread(){
            @Override
            public void run() {
                FormBody.Builder builder = new FormBody.Builder();
                builder.add("uid",uid);
                builder.add("sid",sid);
                builder.add("rec_id",rec_id);
                RequestBody body = builder.build();
                HttpMethods.getInstance().info.checkOrder(AppConstant.CHECKORDER,body)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<CheckOrderBean>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                                addDisposable(d);
                            }

                            @Override
                            public void onNext(CheckOrderBean checkOrderBean) {
                                checkOrderBeanLocal = checkOrderBean;
                            }

                            @Override
                            public void onError(Throwable e) {
                                dispose();
                            }

                            @Override
                            public void onComplete() {
                                mHandler.sendEmptyMessage(0);
                            }
                        });
            }
        }.start();

    }
    private  Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            tv_name.setText(checkOrderBeanLocal.getData().getConsignee().getConsignee());
            tv_mobile.setText(checkOrderBeanLocal.getData().getConsignee().getMobile());
            iv_default.setVisibility(View.VISIBLE);
            tv_address_detail.setText(checkOrderBeanLocal.getData().getConsignee().getProvince_name()+
                    checkOrderBeanLocal.getData().getConsignee().getCity_name()+
                    checkOrderBeanLocal.getData().getConsignee().getDistrict_name()+
                    checkOrderBeanLocal.getData().getConsignee().getAddress());
            if (null != checkOrderBeanLocal.getData().getBonus() && checkOrderBeanLocal.getData().getBonus().size()>0){
            tv_bonus.setText("有可使用");
            }
            tv_price_total.setText(checkOrderBeanLocal.getData().getTotal().getFormated_goods_price());
            tv_total_price_all.setText(checkOrderBeanLocal.getData().getTotal().getFormated_goods_price());
            if (checkOrderBeanLocal.getData().getGoods_list().size()>0){
                mList.addAll(checkOrderBeanLocal.getData().getGoods_list());
                mAdapter.notifyDataSetChanged();
            }
            address_id = checkOrderBeanLocal.getData().getConsignee().getId();
        }
    };

    @OnClick({R.id.rl_address,R.id.ll_bonus,R.id.tv_submit})
    public void onClick(View view){

        switch (view.getId()){
            case R.id.rl_address:
                Bundle bundle = new Bundle();
                bundle.putString("choosingAddress","y");
                ActivityUtils.startActivity(bundle,this,MyAddressActivity.class);
                break;
            case R.id.ll_bonus:
                Bundle bundle1 = new Bundle();
                bundle1.putString("choosingBonus","y");
                ActivityUtils.startActivity(bundle1,this,MyYouhuiActivity.class);
                break;
            case R.id.tv_submit:
                goToPay();
                break;
        }

    }
    private void goToPay(){

        if (null == address_id || address_id.isEmpty()){
            ToastUtils.showShort("请选择收货地址");
            return;
        }

        final FormBody.Builder builder = new FormBody.Builder();

            builder.add("uid",uid);

            builder.add("sid",sid);
        builder.add("pay_id",pay_id);
        builder.add("shipping_id",checkOrderBeanLocal.getData().getShipping_list().get(0).getShipping_id());
        builder.add("address_id",address_id);
        if (null != bonus){
            builder.add("bonus",bonus);
        }
        RequestBody body = builder.build();

        HttpMethods.getInstance().info.orderDone(AppConstant.DONEORDER,body).
                subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OrderDoneBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(OrderDoneBean orderDoneBean) {
                        Bundle bundle = new Bundle();
                        bundle.putString("price",orderDoneBean.getData().getOrder_info().getOrder_amount());
                        ActivityUtils.startActivity(bundle,SubmitOrderActivity.this,GoToPayActivity.class);
                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        dispose();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainThread(ChooseAddressEvent event){
        AddressListBean.DataBean bean = event.getDataBean();
        tv_name.setText(bean.getConsignee());
        tv_mobile.setText(bean.getMobile());
        if (bean.getDefault_address() == 1){
            iv_default.setVisibility(View.VISIBLE);
        }else {
            iv_default.setVisibility(View.GONE);
        }
        tv_address_detail.setText(bean.getProvince_name()+bean.getCity_name()+bean.getDistrict_name()+bean.getAddress());
        address_id = bean.getId();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainThread(BonusChooseEvent event){
        youhuiData = event.getHasChoosed();
        tv_bonus.setText(youhuiData.getType_name());
        tv_bonus_price.setText("￥"+youhuiData.getType_money()+"元");
        tv_total_price_all.setText("￥"+(checkOrderBeanLocal.getData().getTotal().getGoods_price()-Integer.parseInt(youhuiData.getType_money()))+"元");
        bonus = youhuiData.getType_money();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        dispose();
        EventBus.getDefault().unregister(this);
    }
}
